package com.jolink.omiis.wechat.util;

import java.sql.Timestamp;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

/**
 * Gson-Util
 * 
 * @author WangYanqing
 *
 */
public class GsonUtil {

	/**
	 * JSON 字符串格式转 Map
	 * 
	 * @param jsonStr
	 * @return
	 */
	public static Map<String, String> str2Map(String jsonStr) {
		if (StringUtils.isEmpty(jsonStr)) {
			return Collections.EMPTY_MAP;
		}
		Gson gson = new GsonBuilder().disableHtmlEscaping().create();
		Map<String, String> jsonMap = gson.fromJson(jsonStr, new TypeToken<Map<String, String>>() {
		}.getType());
		return jsonMap;
	}

	/**
	 * 普通 java 对象转 Json-String
	 * 
	 * @param obj
	 * @return
	 */
	public static String obj2Json(Object obj) {
		Gson gson = new GsonBuilder().create();
		String jsonStr = gson.toJson(obj);
		return jsonStr;
	}

	/**
	 * Gson提供的对象转换
	 * 
	 * @param jsonE
	 * @return
	 */
	public static String jsonElement2Json(JsonElement jsonE) {
		Gson gson = new GsonBuilder().disableHtmlEscaping().create();
		String jsonStr = gson.toJson(jsonE);
		return jsonStr;
	}

	public static JsonObject json2JsonObject(String json) {
		JsonParser parser = new JsonParser();
		JsonElement jsonElement = parser.parse(json);
		return jsonElement.getAsJsonObject();
	}

	public static <T> T json2Object(String json, Class<T> clazz) {
		Gson gson = new GsonBuilder().disableHtmlEscaping().create();
		return gson.fromJson(json, clazz);
	}

	public static String map2Json(Map<String, Object> map) {
		JsonObject root = new JsonObject();
		for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
			String key = it.next();
			Object value = map.get(key);
			String newValue = null;
			if (value instanceof Timestamp) {
				newValue = DateUtil.transfer2DateString((Timestamp) value, "yyyy-MM-dd HH:mm:ss");
			} else if (value instanceof String) {
				newValue = (String) value;
			}
			root.addProperty(key, newValue);
		}
		return root.toString();
	}
}
